<?php
namespace app\api\logic;
use think\Db;
class Teacher extends Base{

    private $AccountInfo = [];

    public function __construct()
    {
        parent::__construct();
    }

    //教师名片页信息
    public function tinfo($param)
    {   
        $tid = isset($param['tid'])?intval($param['tid']):0;
        $where[] =['id','=',$tid];
        $where[] =['status','=',1];
        $teacher=Db::name('teacher')->where($where)->find();
        if (!$teacher){
            $this->return_data['Msg'] = "无此老师";
            return $this->return_data;
        }
        $teacher['description'] = str_replace('<img', '<img width="100%"', $teacher['description']);
        $teacher['cover'] = get_basecover_img($teacher['avatar']);
        $teacher['wxcode'] = get_basecover_img($teacher['wxcode']);
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = ['teacher'=>$teacher];
        return $this->return_data;
    }
    //教师名片页信息
    public function teacherInfo($param)
    {
        $tid = isset($param['tid'])?intval($param['tid']):0;
        $where[] =['id','=',$tid];
        $where[] =['status','=',1];
        $teacher=Db::name('teacher')->where($where)->find();
        if (!$teacher){
            $this->return_data['Msg'] = "无此老师";
            return $this->return_data;
        }
        $teacher['cover'] = get_basecover_img($teacher['avatar']);
        $teacher['wxcode'] = get_basecover_img($teacher['wxcode']);
        $teacher['description'] = str_replace('<img', '<img width="100%"', $teacher['description']);
        $sid = $teacher['sid'];
        $info= Db::name('store')->where([['id','=',$sid],['status','=',1]])->find();
        if (!$info){
            $this->return_data['Msg'] = "门店过期或无此门店";
            return $this->return_data;
        }
        /*
        $store_photos = Db::name('store_photo')->where([['sid','=',$sid]])->select();
        $pts = [];
        foreach($store_photos as $v){
          $pts[] = get_newpic_url($v['path']);
        }
        $info['store_photos'] = $pts;
        */
        $info['pics1'] = '';
        if($info['pic1'])
          $info['pics1'] = get_newpic_url($info['pic1']);
        $info['pics2'] = '';
        if($info['pic2'])
          $info['pics2'] = get_newpic_url($info['pic2']);
        $info['pics3'] = '';
        if($info['pic3'])
          $info['pics3'] = get_newpic_url($info['pic3']);
        $info['vpics1'] = '';
        if($info['vpic1'])
          $info['vpics1'] = get_newpic_url($info['vpic1']);
        $info['vpics2'] = '';
        if($info['vpic2'])
          $info['vpics2'] = get_newpic_url($info['vpic2']);
        $info['vpics3'] = '';
        if($info['vpic3'])
          $info['vpics3'] = get_newpic_url($info['vpic3']);
        $info['store_photos'] = str_replace('<img', '<img width="100%"', $info['store_photos']);

        $info['wxcode'] = get_basecover_img($info['wxcode']);
        
        $activity = Db::name('activity')->where([['status','=',1],['sid','=',$sid]])->find();
        $activity['cover'] = ''; 
        if(isset($activity['pic']))
          $activity['cover'] = get_newpic_url($activity['pic']); 
        $appointing = Db::name('appointing')->where([['sid','=',$sid]])->limit(20)->select();


        // 门店集合
        if ($info['is_group']==1) {
          $address = explode(',', $info['address']);
          $group_store = explode(',', $info['group_store']);
          $info['group_store_arr'] = [];
          if (count($group_store)) {
            foreach ($group_store as $key => $value) {
              $info['group_store_arr'][] = ['name'=>$value,'address'=>$address[$key]];
            }
          }
        }
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = ['teacher'=>$teacher,'store'=>$info,'activity'=>$activity,'appointing'=>$appointing];
        return $this->return_data;
    }


    // 课时日历
    public function calendar($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        if (!$uid){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        $user = Db::name('user')->where([['id','=',$uid]])->find();
        if (!$user) {
            $this->return_data['Msg'] = "不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->field('id')->where('user_id',$uid)->find();
        if (!$teacher){
            $this->return_data['Msg'] = " 不存在该老师数据";
            return $this->return_data;
        }
        $data = [];
        $data2 = [];
        $classtime = Db::name('course')->alias('c')->leftJoin('classtime ct','c.id=ct.course_id and ct.status=1')->field('ct.*')->where('c.teacher_id='.$teacher['id'].' and c.status=1')->order('begin_time ASC')->select();
        if ($classtime) {
            foreach ($classtime as $key => $value) {
                $data[$key]['date'] = date('Y-m-d',$value['begin_time']);
                $data[$key]['info'] = '打点描述';
                $data[$key]['data'] = ['custom'=>'自定义信息','name'=>'自定义消息头','color'=>'#E7402E'];
            }
        }
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = $data;
        return $this->return_data;
    }


    // 课程列表
    public function dayCourse($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $date = isset($input['date']) ? $input['date']:date('Y-m-d');
        if (!$uid){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        $user = Db::name('user')->where([['id','=',$uid]])->find();
        if (!$user) {
            $this->return_data['Msg'] = "不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->field('id')->where('user_id',$uid)->find();
        if (!$teacher){
            $this->return_data['Msg'] = " 不存在该老师数据";
            return $this->return_data;
        }
        $date_begin = strtotime($date);
        $date_end = $date_begin+86400;
        $data = [];
        $classtime = Db::name('course')->alias('c')->leftJoin('classtime ct','c.id=ct.course_id')->field('c.id,c.name,c.sid,c.classes_name,c.teacher_name,c.classroom_name,c.address,c.summary,ct.begin_time,ct.end_time,ct.no,ct.id as ctid')->where('c.teacher_id='.$teacher['id'].' and c.status=1 and ct.status=1 and ct.begin_time>'.$date_begin.' and ct.begin_time<'.$date_end)->order('ct.begin_time ASC')->group('c.id')->select();
        if (isset($classtime[0]['id']) && $classtime[0]['id']) {
            foreach ($classtime as $key => &$value) {
                $store_name = Db::name('store')->where('id',$value['sid'])->value('name');
                $value['classes_name'] = $store_name.$value['classes_name'];
                $value['begin_time'] = date('H:i',$value['begin_time']);
                $value['end_time'] = date('H:i',$value['end_time']);
            }
        }
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = $classtime;
        return $this->return_data;
    }


    // 课程学生列表
    public function classStudent($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $classtime_id = isset($input['classtime_id']) ? $input['classtime_id']:0;
        if (!$uid || !$classtime_id){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        $user = Db::name('user')->where([['id','=',$uid]])->find();
        if (!$user) {
            $this->return_data['Msg'] = "不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->field('id')->where('user_id',$uid)->find();
        if (!$teacher){
            $this->return_data['Msg'] = " 不存在该老师数据";
            return $this->return_data;
        }
        $classtime = Db::name('classtime')->where(['id'=>$classtime_id,'status'=>1])->find();
        if (!$classtime) {
            $this->return_data['Msg'] = " 不存在该课时数据";
            return $this->return_data;
        }
        $course = Db::name('course')->field('id,name,classes_name')->where('id',$classtime['course_id'])->find();
        if (!$classtime) {
            $this->return_data['Msg'] = " 不存在该课程";
            return $this->return_data;
        }
        $student = Db::name('user_course')->alias('uc')->leftJoin('user u','u.id=uc.user_id')->field('u.photo,u.id,u.name,u.avatar')->where([['uc.course_id','=',$classtime['course_id']],['uc.status','in',[1,2]],['u.status','=',1]])->select();
        if ($student) {
            foreach ($student as $key => &$value) {
                $value['is_comment'] = intval(Db::name('user_comment')->where(['classtime_id'=>$classtime_id,'user_id'=>$value['id'],'teacher_id'=>$teacher['id']])->value('id'));
                $value['is_sign'] = Db::name('user_signin')->where(['classtime_id'=>$classtime_id,'user_id'=>$value['id']])->order('id DESC')->value('status');
                if (!$value['is_sign']) {
                    $value['is_sign'] = 0;
                }
                if (!$value['photo']) {
                    $value['photo'] = $value['avatar'];
                } else {
                    $value['photo'] = config('upload_domain').$value['photo'];
                }
            }
        }
        $course['begin_time'] = date('H:i',$classtime['begin_time']);
        $course['end_time'] = date('H:i',$classtime['end_time']);
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = $student;
        $this->return_data["Course"] = $course;
        return $this->return_data;
    }


    // 点评
    public function comment($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        $student_id = isset($input['student_id']) ? $input['student_id']:0;
        $classtime_id = isset($input['classtime_id']) ? $input['classtime_id']:0;
        $content = isset($input['content']) ? htmlentities($input['content']):'';
        $img = isset($input['img']) ? htmlentities($input['img']):'';
        if (!$uid || !$student_id || !$classtime_id || !$sid){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        if (!$content) {
            $this->return_data['Msg'] = " 请输入内容";
            return $this->return_data;
        }
        if (!$img) {
            $this->return_data['Msg'] = " 请上传图片";
            return $this->return_data;
        }
        $user = Db::name('user')->where([['id','=',$uid]])->find();
        if (!$user) {
            $this->return_data['Msg'] = "不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->field('id,name')->where('user_id',$uid)->find();
        if (!$teacher){
            $this->return_data['Msg'] = " 不存在该老师数据";
            return $this->return_data;
        }
        $classtime = Db::name('classtime')->where('id',$classtime_id)->find();
        $data['teacher_id'] = $teacher['id'];
        $data['user_id'] = $student_id;
        $data['content'] = $content;
        $data['img'] = $img;
        $data['classtime_id'] = $classtime_id;
        $data['course_id'] = $classtime['course_id'];
        $data['no'] = $classtime['no'];
        $data['createtime'] = time();
        $is_insert = Db::name('user_comment')->insertGetId($data);
        if (!$is_insert) {
            $this->return_data['Msg'] = "点评出错";
            return $this->return_data;
        }

        // 点评通知
        $template_id = 'peRE9y10cluGNAQajzddXdpq_jDvOj8B3hX5Ulf9Ldo';
        $page = 'orderPackages/pages/myChild/growthRecord?notice=1&sid='.$sid;
        
        $PublicsLogic = Controller('publics','logic');
        $course = Db::name('course')->where('id=(select course_id from zsy_classtime where id='.$classtime_id.')')->field('*')->find();
        $students = Db::name('user')->alias('u')->field('u.name,u.fwhopenid')->where(['u.id'=>$student_id])->find();
        if (isset($students['fwhopenid']) && $students['fwhopenid']) {
              $openid = $students['fwhopenid'];
              $data = [
                  'first' => ['value' => '老师对你今天上课的表现进行了点评'],
                  'keyword1' => ['value' => $students['name']],
                  'keyword2' => ['value' => $course['name']],
                  'keyword3' => ['value' => $teacher['name']],
                  'remark' => ['value' => '快去看看吧！'],
              ];
              $res = $PublicsLogic->send_template_message($template_id, $page, $data, $openid);
        }
        $this->return_data["Code"] = 0;
        $this->return_data["Msg"] = '成功';
        return $this->return_data;
    }

    // 签到
    public function studentSign($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        $student_id = isset($input['student_id']) ? $input['student_id']:0;
        $classtime_id = isset($input['classtime_id']) ? $input['classtime_id']:0;
        $status = isset($input['status']) ? $input['status']:0;
        if (!$uid || !$student_id || !$classtime_id || !$sid){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        $user = Db::name('user')->where([['id','=',$uid]])->find();
        if (!$user) {
            $this->return_data['Msg'] = "不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->field('id')->where('user_id',$uid)->find();
        if (!$teacher){
            $this->return_data['Msg'] = " 不存在该老师数据";
            return $this->return_data;
        }
        $where = [];
        $where[] = ['user_id','=',$student_id];
        $where[] = ['classtime_id','=',$classtime_id];
        $where[] = ['status','>',0];
        if (Db::name('user_signin')->where($where)->find()) {
            $this->return_data['Msg'] = " 不能重复签到";
            return $this->return_data;
        }
        $user_course = Db::name('user_course')->where('user_id='.$student_id.' and course_id=(select course_id from zsy_classtime where id='.$classtime_id.') and status in (1,2)')->find();
        if ($user_course['classtime_surplus']<=0) {
            $this->return_data['Msg'] = " 该学生课程已上完";
            return $this->return_data;
        }
        Db::startTrans();
        try {
            if ($user_course['classtime_surplus']==$user_course['classtime_sum']) {
                $update_data['status'] = 2;
            }
            $update_data['classtime_surplus'] = $user_course['classtime_surplus']-1;
            $update_data['updatetime'] = time();
            // 已完课
            if ($update_data['classtime_surplus']==0) {
                $update_data['status'] = 3;
            }
            $is_update = Db::name('user_course')->where(['id'=>$user_course['id']])->update($update_data);
            if (!$is_update) {
                Db::rollBack();
                $this->return_data['Msg'] = "签到出错";
                return $this->return_data;
            }
            $classtime = Db::name('classtime')->where('id',$classtime_id)->find();
            $data['user_id'] = $student_id;
            $data['classtime_id'] = $classtime_id;
            $data['course_id'] = $classtime['course_id'];
            $data['no'] = $classtime['no'];
            $data['teacher_id'] = $teacher['id'];
            $data['status'] = $status;
            $data['createtime'] = time();
            $is_insert = Db::name('user_signin')->insertGetId($data);
            if (!$is_insert) {
                Db::rollBack();
                $this->return_data['Msg'] = "签到出错";
                return $this->return_data;
            }

            // 课程消耗通知
            if (in_array($status, [1,2])) {
                $template_id = '2xko_kK6ANHEaLo5kqf1w7c-bFsn4n6aJnE67N65fSc';
                $page = 'orderPackages/pages/myChild/myClassTime?notice=1&sid='.$sid;
                $PublicsLogic = Controller('publics','logic');
                $course = Db::name('course')->where(['id'=>$user_course['course_id']])->field('*')->find();
                $students = Db::name('user')->alias('u')->field('u.name,u.fwhopenid')->where(['u.id'=>$student_id])->find();
                $classtime = Db::name('classtime')->where('id',$classtime_id)->find();
                if (isset($students['fwhopenid']) && $students['fwhopenid']) {
                      $openid = $students['fwhopenid'];
                      $data = [
                          'first' => ['value' => '你好，你已成功消耗课时。'],
                          'keyword1' => ['value' => $students['name']],
                          'keyword2' => ['value' => $course['name']],
                          'keyword3' => ['value' => '1课时'],
                          'keyword4' => ['value' => date('Y-m-d H:i',$classtime['begin_time'])],
                          'keyword5' => ['value' => $update_data['classtime_surplus'].'课时'],
                          'remark' => ['value' => '快去看看吧！'],
                      ];
                      $res = $PublicsLogic->send_template_message($template_id, $page, $data, $openid);
                }
            }
            Db::commit();
            $this->return_data["Code"] = 0;
            $this->return_data["Msg"] = '成功';
            return $this->return_data;
        } catch (\Exception $e) {
            Db::rollBack();
            $this->return_data['Msg'] = "签到出错";
            return $this->return_data;
        }
    }

    // 课时备注
    public function classtimeRemark($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $classtime_id = isset($input['classtime_id']) ? $input['classtime_id']:0;
        $remark = isset($input['remark']) ? htmlentities($input['remark']):'';
        if (!$uid || !$classtime_id){
            $this->return_data['Msg'] = " 参数错误";
            return $this->return_data;
        }
        $user = Db::name('user')->where([['id','=',$uid]])->find();
        if (!$user) {
            $this->return_data['Msg'] = "不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->field('id')->where('user_id',$uid)->find();
        if (!$teacher){
            $this->return_data['Msg'] = " 不存在该老师数据";
            return $this->return_data;
        }
        $data['remark'] = $remark;
        $data['updatetime'] = time();
        $is_update = Db::name('classtime')->where(['id'=>$classtime_id])->update($data);
        if (!$is_update) {
            $this->return_data['Msg'] = "备注出错";
            return $this->return_data;
        }
        $this->return_data["Code"] = 0;
        $this->return_data["Msg"] = '成功';
        return $this->return_data;
    }



    // 请假列表
    public function askForLeaveList($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        if (!$uid || !$sid) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
        if (!$user) {
            $this->return_data['Msg'] = " 不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
        if (!$teacher) {
            $this->return_data['Msg'] = " 不存在该老师";
            return $this->return_data;
        }
        $askforleave = Db::name('askforleave')->where(['teacher_id'=>$teacher['id']])->order('id desc')->select();
        if ($askforleave) {
            $UserLogic = new \app\api\logic\User();
            foreach ($askforleave as $key => &$value) {
                $value['student_name'] = Db::name('user')->where('id',$value['user_id'])->value('name');
                $value['course_name'] = '';
                $value['course_date'] = '';
                $course = Db::name('classtime')->alias('ct')->leftJoin('course c','c.id=ct.course_id')->field('c.name,ct.begin_time')->where(['ct.id'=>$value['classtime_id']])->find();
                if ($course) {
                    $value['course_name'] = $course['name'];
                    $value['course_date'] = date('Y-m-d H:i:s',$course['begin_time']);
                }
                $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                $value['status'] = $UserLogic->askforleave_status[$value['status']];
            }
        }
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = $askforleave;
        return $this->return_data;
    }

    // 请假详情
    public function askForLeaveInfo($input)
    {
        $sid = isset($input['sid']) ? $input['sid']:0;
        $id = isset($input['id']) ? $input['id']:0;
        if (!$sid || !$id) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $askforleave = Db::name('askforleave')->where(['id'=>$id])->find();
        if (!$askforleave) {
            $this->return_data['Msg'] = " 找不到该请假申请";
            return $this->return_data;
        }
        $askforleave['createtime'] = date('Y-m-d H:i:s',$askforleave['createtime']);
        $askforleave['student_name'] = Db::name('user')->where('id',$askforleave['user_id'])->value('name');
        $course = Db::name('classtime')->alias('ct')->leftJoin('course c','c.id=ct.course_id')->field('c.id,c.name,c.teacher_name,c.classroom_name,c.classes_name,c.address,ct.begin_time,ct.end_time')->where(['ct.id'=>$askforleave['classtime_id']])->find();
        $askforleave['course_id'] = $course['id'];
        $askforleave['course_name'] = $course['name'];
        $askforleave['teacher_name'] = $course['teacher_name'];
        $askforleave['classroom_name'] = $course['classroom_name'];
        $askforleave['classes_name'] = $course['classes_name'];
        $askforleave['address'] = $course['address'];
        $UserLogic = new \app\api\logic\User();
        $askforleave['status'] = $UserLogic->askforleave_status[$askforleave['status']];
        $askforleave['begin_time'] = date('H:i',$course['begin_time']);
        $askforleave['end_time'] = date('H:i',$course['end_time']);
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = $askforleave;
        return $this->return_data;
    }


    // 请假审核
    public function replyForLeave($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        $id = isset($input['id']) ? $input['id']:0;
        $status = isset($input['status']) ? $input['status']:0;
        $reply = isset($input['reply']) ? $input['reply']:'';
        if (!$uid || !$sid || !$id || !$status) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
        if (!$user) {
            $this->return_data['Msg'] = " 不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
        if (!$teacher) {
            $this->return_data['Msg'] = " 不存在该老师";
            return $this->return_data;
        }
        $askforleave = Db::name('askforleave')->where(['teacher_id'=>$teacher['id'],'id'=>$id])->find();
        if (!$askforleave) {
            $this->return_data['Msg'] = " 找不到该请假申请";
            return $this->return_data;
        }
        if ($askforleave['status']!=0) {
            $this->return_data['Msg'] = " 该请假申请已经审核过了";
            return $this->return_data;
        }
        Db::startTrans();
        try {
            $is_update = Db::name('askforleave')->where('id',$id)->update(['status'=>$status,'reply'=>$reply,'updatetime'=>time()]);
            if (!$is_update) {
                Db::rollBack();
                $this->return_data['Msg'] = " 更新失败";
                return $this->return_data;
            }
            $course = Db::name('classtime')->alias('ct')->leftJoin('course c','c.id=ct.course_id')->field('c.id,c.name,ct.no')->where(['ct.id'=>$askforleave['classtime_id']])->find();
            if ($status==1) {
                $data['classtime_id'] = $askforleave['classtime_id'];
                $data['user_id'] = $askforleave['user_id'];
                $data['status'] = 3;
                $data['teacher_id'] = $askforleave['teacher_id'];
                $data['course_id'] = $course['id'];
                $data['no'] = $course['no'];
                $data['createtime'] = time();
                $is_insert = Db::name('user_signin')->insertGetId($data);
                if (!$is_insert) {
                    Db::rollBack();
                    $this->return_data['Msg'] = " 更新失败";
                    return $this->return_data;
                }
            }

            // 请假结果通知
            $student = Db::name('user')->where('id='.$askforleave['user_id'])->field('name,fwhopenid')->find();
            if ($student['fwhopenid']) {
                $template_id = 'rWTHCSrjgvIgf1NHbCTCR8sL4-rS4ygf556UlHLPp-k';
                $openid = $student['fwhopenid'];
                $page = 'orderPackages/pages/myChild/myLeave?notice=1&sid='.$sid;
                if ($status==1) {
                    $keyword3 = '通过';
                } else {
                    $keyword3 = '不通过，原因：'.$reply;
                }
                $data = [
                    'first' => ['value' => $student['name'].'同学，你的请假申请已处理'],
                    'keyword1' => ['value' => $student['name']],
                    'keyword2' => ['value' => $teacher['name']],
                    'keyword3' => ['value' => $keyword3],
                    'remark' => ['value' => '请查看！'],
                ];
                write_log(json_encode($data));
                $PublicsLogic = new \app\api\logic\Publics();
                $res = $PublicsLogic->send_template_message($template_id, $page, $data, $openid);
            }
            Db::commit();
            $this->return_data["Code"] = 0;
            $this->return_data['Msg'] = " 审核成功";
            return $this->return_data;
        } catch (\Exception $e) {
            Db::rollBack();
            $this->return_data['Msg'] = " 更新失败";
            return $this->return_data;
        }
    }



    // 补课申请列表
    public function makeUpLessonsList($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        if (!$uid || !$sid) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
        if (!$user) {
            $this->return_data['Msg'] = " 不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
        if (!$teacher) {
            $this->return_data['Msg'] = " 不存在该老师";
            return $this->return_data;
        }
        $makeuplesson = Db::name('makeuplesson')->where(['teacher_id'=>$teacher['id']])->order('id desc')->select();
        if ($makeuplesson) {
            $UserLogic = new \app\api\logic\User();
            foreach ($makeuplesson as $key => &$value) {
                $value['student_name'] = Db::name('user')->where('id',$value['user_id'])->value('name');
                $value['course_name'] = '';
                $value['course_date'] = '';
                $course = Db::name('classtime')->alias('ct')->leftJoin('course c','c.id=ct.course_id')->field('c.name,ct.begin_time')->where(['ct.id'=>$value['classtime_id']])->find();
                if ($course) {
                    $value['course_name'] = $course['name'];
                    $value['course_date'] = date('Y-m-d H:i:s',$course['begin_time']);
                }
                $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                $value['makeup_time'] = date('Y-m-d H:i:s',$value['makeup_time']);
                $value['status'] = $UserLogic->askforleave_status[$value['status']];
            }
        }
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = $makeuplesson;
        return $this->return_data;
    }

    // 补课申请详情
    public function makeUpLessonsInfo($input)
    {
        $sid = isset($input['sid']) ? $input['sid']:0;
        $id = isset($input['id']) ? $input['id']:0;
        if (!$sid || !$id) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $makeuplesson = Db::name('makeuplesson')->where(['id'=>$id])->find();
        if (!$makeuplesson) {
            $this->return_data['Msg'] = " 找不到该补课申请";
            return $this->return_data;
        }
        $makeuplesson['makeup_time'] = date('Y-m-d H:i',$makeuplesson['makeup_time']);
        $askforleave = Db::name('askforleave')->where(['id'=>$makeuplesson['askforleave_id']])->find();
        if (!$askforleave) {
            $this->return_data['Msg'] = " 找不到该请假申请";
            return $this->return_data;
        }
        $makeuplesson['createtime'] = date('Y-m-d H:i:s',$askforleave['createtime']);
        $course = Db::name('classtime')->alias('ct')->leftJoin('course c','c.id=ct.course_id')->field('c.id,c.name,c.teacher_name,c.classroom_name,c.classes_name,c.address,ct.begin_time,ct.end_time')->where(['ct.id'=>$makeuplesson['classtime_id']])->find();
        $makeuplesson['course_id'] = $course['id'];
        $makeuplesson['student_name'] = Db::name('user')->where('id',$makeuplesson['user_id'])->value('name');
        $makeuplesson['course_name'] = $course['name'];
        $makeuplesson['askforleave_reason'] = $askforleave['reason'];
        $makeuplesson['askforleave_type'] = $askforleave['type'];
        $makeuplesson['teacher_name'] = $course['teacher_name'];
        $makeuplesson['classroom_name'] = $course['classroom_name'];
        $makeuplesson['classes_name'] = $course['classes_name'];
        $makeuplesson['address'] = $course['address'];
        $UserLogic = new \app\api\logic\User();
        $makeuplesson['status'] = $UserLogic->askforleave_status[$makeuplesson['status']];
        $makeuplesson['begin_time'] = date('H:i',$course['begin_time']);
        $makeuplesson['end_time'] = date('H:i',$course['end_time']);
        $this->return_data["Code"] = 0;
        $this->return_data["Data"] = $makeuplesson;
        return $this->return_data;
    }


    // 补课审核
    public function replyMakeUpLessons($input)
    {
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        $id = isset($input['id']) ? $input['id']:0;
        $status = isset($input['status']) ? $input['status']:0;
        $reply = isset($input['reply']) ? $input['reply']:'';
        if (!$uid || !$sid || !$id || !$status) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
        if (!$user) {
            $this->return_data['Msg'] = " 不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
        if (!$teacher) {
            $this->return_data['Msg'] = " 不存在该老师";
            return $this->return_data;
        }
        $makeuplesson = Db::name('makeuplesson')->where(['teacher_id'=>$teacher['id'],'id'=>$id])->find();
        if (!$makeuplesson) {
            $this->return_data['Msg'] = " 找不到该补课申请";
            return $this->return_data;
        }
        if ($makeuplesson['status']!=0) {
            $this->return_data['Msg'] = " 该补课申请已经审核过了";
            return $this->return_data;
        }
        Db::startTrans();
        try {
            $is_update = Db::name('makeuplesson')->where('id',$id)->update(['status'=>$status,'reply'=>$reply,'updatetime'=>time()]);
            if (!$is_update) {
                Db::rollBack();
                $this->return_data['Msg'] = " 更新失败";
                return $this->return_data;
            }

            // 补课结果通知
            $student = Db::name('user')->where('id='.$makeuplesson['user_id'])->field('name,fwhopenid')->find();
            if ($student['fwhopenid']) {
                $template_id = 'GzylwMO_TbVPtuR3bV6OawZlbWa8dqmRlJBIJV-kwAU';
                $openid = $student['fwhopenid'];
                $page = 'orderPackages/pages/admin/lessons?notice=1&sid='.$sid;
                if ($status==1) {
                    $keyword3 = '通过';
                } else {
                    $keyword3 = '不通过，原因：'.$reply;
                }
                $course = Db::name('classtime')->alias('ct')->leftJoin('course c','c.id=ct.course_id')->field('c.id,c.name,ct.no,ct.begin_time')->where(['ct.id'=>$makeuplesson['classtime_id']])->find();
                $data = [
                    'first' => ['value' => $student['name'].'同学，你的补课申请已处理'],
                    'keyword1' => ['value' => $course['name']],
                    'keyword2' => ['value' => $teacher['name']],
                    'keyword3' => ['value' => date('Y-m-d H:i',$course['begin_time'])],
                    'keyword4' => ['value' => date('Y-m-d H:i',$makeuplesson['makeup_time'])],
                    'keyword5' => ['value' => $keyword3],
                    'remark' => ['value' => '请知晓，及时补课！'],
                ];
                write_log(json_encode($data));
                $PublicsLogic = new \app\api\logic\Publics();
                $res = $PublicsLogic->send_template_message($template_id, $page, $data, $openid);
            }
            Db::commit();
            $this->return_data["Code"] = 0;
            $this->return_data['Msg'] = " 审核成功";
            return $this->return_data;
        } catch (\Exception $e) {
            Db::rollBack();
            $this->return_data['Msg'] = " 更新失败";
            return $this->return_data;
        }
    }



    // 课件板块
    public function coursewareCourse($input)
    {
        $pid = isset($input['pid']) ? $input['pid']:0;
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        if (!$uid) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
        if (!$user) {
            $this->return_data['Msg'] = " 不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
        if (!$teacher) {
            $this->return_data['Msg'] = " 不存在该老师";
            return $this->return_data;
        }
        $courseware_course = Db::name('courseware_course')->field('id as value,name as label,icon,level')->order('sort ASC,id ASC')->where(['pid'=>$pid,'status'=>1])->select();
        if (count($courseware_course)) {
            foreach ($courseware_course as $key => $value) {
                $flag = 0;
                $courseware_course[$key]['icon'] = config('upload_domain').$value['icon'];
                if ($value['level']!=3) {
                    $children1 = Db::name('courseware_course')->field('id as value,name as label,icon,level')->order('sort ASC,id ASC')->where(['pid'=>$value['value'],'status'=>1])->select();
                    if (count($children1)) {
                        foreach ($children1 as $k => $v) {
                            $children1[$k]['icon'] = config('upload_domain').$v['icon'];
                            if ($v['level']!=3) {
                                $children2 = Db::name('courseware_course')->field('id as value,name as label,icon,level')->where(['pid'=>$v['value'],'status'=>1])->order('sort ASC,id ASC')->select();
                                if (count($children2)) {
                                    foreach ($children2 as $k2 => $v2) {
                                        $children2[$k2]['icon'] = config('upload_domain').$v2['icon'];
                                        if ($value['label']=='逻辑思维'){
                                            $where = [];
                                            $where[] = ['ca.teacher_id','=',$teacher['id']];
                                            $where[] = ['ca.type','=',2];
                                            $where[] = ['ca.status','=',1];
                                            $where[] = ['c.status','=',1];
                                            $where[] = ['cc.status','=',1];
                                            $where[] = ['ca.course_id','=',$v2['value']];
                                            $where[] = ['ca.start_time','<',time()];
                                            $where[] = ['ca.end_time','>',time()];
                                            $courseware  = Db::name('courseware_authorize')->alias('ca')
                                                  ->leftJoin('courseware c','ca.course_id=c.course_id')
                                                  ->leftJoin('courseware_course cc','c.course=cc.name')
                                                  ->field('c.id,c.name')
                                                  ->where($where)->find();
                                            if ($courseware) $flag=1;
                                        }
                                    }
                                }
                                $children1[$k]['children'] = $children2;
                            }
                        }
                    }
                    $courseware_course[$key]['children'] = $children1;
                }
            }
        }
        // if ($flag==0 && $pid==0) {
        //     unset($courseware_course[$key]);
        // }
        $this->return_data["Code"] = 0;
        $this->return_data['Msg'] = "成功";
        $this->return_data['Data'] = $courseware_course;
        return $this->return_data;
    }


    // 课件列表
    public function coursewareList($input)
    {
        $courseware_course_id = isset($input['courseware_course_id']) ? $input['courseware_course_id']:0;
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        if (!$courseware_course_id || !$uid) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
        if (!$user) {
            $this->return_data['Msg'] = " 不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
        if (!$teacher) {
            $this->return_data['Msg'] = " 不存在该老师";
            return $this->return_data;
        }
        $where[] = ['ca.teacher_id','=',$teacher['id']];
        $where[] = ['ca.type','=',2];
        $where[] = ['ca.status','=',1];
        $where[] = ['c.status','=',1];
        $where[] = ['cc.status','=',1];
        $where[] = ['ca.course_id','=',$courseware_course_id];
        $courseware  = Db::name('courseware_authorize')->alias('ca')
              ->leftJoin('courseware c','ca.course_id=c.course_id')
              ->leftJoin('courseware_course cc','c.course=cc.name')
              ->field('c.id,c.name')
              ->where($where)
              ->order('c.id desc')->select();
        $this->return_data["Code"] = 0;
        $this->return_data['Msg'] = "成功";
        $this->return_data['Data'] = $courseware;
        return $this->return_data;
    }


    // 课件详情
    // public function coursewareInfo($input)
    // {
    //     $id = isset($input['id']) ? $input['id']:0;
    //     $uid = isset($input['user_id']) ? $input['user_id']:0;
    //     $sid = isset($input['sid']) ? $input['sid']:0;
    //     if (!$id || !$uid) {
    //         $this->return_data['Msg'] = " 缺少参数";
    //         return $this->return_data;
    //     }
    //     $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
    //     if (!$user) {
    //         $this->return_data['Msg'] = " 不存在该用户";
    //         return $this->return_data;
    //     }
    //     $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
    //     if (!$teacher) {
    //         $this->return_data['Msg'] = " 不存在该老师";
    //         return $this->return_data;
    //     }
    //     $courseware = Db::name('courseware')->where(['id'=>$id])->find();
    //     $courseware_authorize = Db::name('courseware_authorize')->where(['course_id'=>$courseware['course_id'],'status'=>1,'teacher_id'=>$teacher['id'],'type'=>2])->find();
    //     if (!$courseware_authorize) {
    //         $this->return_data['Msg'] = " 您暂无权限查看";
    //         return $this->return_data;
    //     }
    //     $courseware['has_video'] = 0;
    //     $courseware['has_pdf'] = 0;
    //     $courseware['video'] = [];
    //     $courseware['pdf'] = [];
    //     if (isset($courseware['file']) && $courseware['file']) {
    //         $courseware['file'] = json_decode($courseware['file'],1);
    //         if (is_array($courseware['file']) && count($courseware['file'])) {
    //             foreach ($courseware['file'] as $key => &$value) {
    //                 $multi_file = [];
    //                 $ex = explode(',', trim($value[1]));
    //                 if (count($ex)) {
    //                     foreach ($ex as $k => &$mf) {
    //                         $mf_name = Db::name('file')->where(['path'=>$mf])->value('name');
    //                         if (!$mf_name) {
    //                             if ($value[2]=='视频') {
    //                                 $mf_name = '视频';
    //                             } else {
    //                                 $mf_name = '文件';
    //                             }
    //                         }
    //                         $mf = config('upload_domain').$mf;
    //                         $multi_file[$k] = ['mf_name'=>$mf_name,'mf'=>$mf];
    //                     }
    //                 }
    //                 $value[3] = $multi_file;
    //                 if ($value[2]=='视频') {
    //                     $courseware['has_video'] = 1;
    //                     $courseware['video'] = array_merge($courseware['video'],$multi_file);
    //                 } else {
    //                     $courseware['has_pdf'] = 1;
    //                     $courseware['pdf'] = array_merge($courseware['pdf'],$multi_file);
    //                 }
                    
    //                 // $multi_file = explode(',', trim($value[1]));
    //                 // if (count($multi_file)) {
    //                 //     foreach ($multi_file as &$mf) {
    //                 //         $mf = config('upload_domain').$mf;
    //                 //     }
    //                 // }
    //                 // $value[3] = $multi_file;
    //                 // if ($value[2]=='视频') {
    //                 //     $courseware['has_video'] = 1;
    //                 //     $courseware['video'] = array_merge($courseware['video'],$multi_file);
    //                 // } else {
    //                 //     $courseware['has_pdf'] = 1;
    //                 //     $courseware['pdf'] = array_merge($courseware['pdf'],$multi_file);
    //                 // }
    //             }
    //         }
    //     }
    //     $pid3 = $courseware['course_id'];
    //     $courseware_course_name3 = $courseware['course'];
    //     $courseware_course2 = Db::name('courseware_course')->where(['id'=>$pid3])->field('pid,name')->find();
    //     $pid2 = $courseware_course2['pid'];
    //     $courseware_course_name2 = $courseware_course2['name'];
    //     $courseware_course1 = Db::name('courseware_course')->where(['id'=>$pid2])->field('pid,name')->find();
    //     $pid1 = $courseware_course2['pid'];
    //     $courseware_course_name1 = $courseware_course1['name'];
    //     $this->return_data["Code"] = 0;
    //     $this->return_data['Msg'] = "成功";
    //     $this->return_data['Data'] = ['courseware'=>$courseware,'courseware_course_name3'=>$courseware_course_name3,'courseware_course_name2'=>$courseware_course_name2,'courseware_course_name1'=>$courseware_course_name1];
    //     return $this->return_data;
    // }


    // 课件详情(主题下的所有详情)
    public function coursewareInfo($input)
    {
        $id = isset($input['id']) ? $input['id']:0;
        $uid = isset($input['user_id']) ? $input['user_id']:0;
        $sid = isset($input['sid']) ? $input['sid']:0;
        if (!$id || !$uid) {
            $this->return_data['Msg'] = " 缺少参数";
            return $this->return_data;
        }
        $user = Db::name('user')->where(['sid'=>$sid,'id'=>$uid,'is_teacher'=>1])->find();
        if (!$user) {
            $this->return_data['Msg'] = " 不存在该用户";
            return $this->return_data;
        }
        $teacher = Db::name('teacher')->where(['user_id'=>$uid])->find();
        if (!$teacher) {
            $this->return_data['Msg'] = " 不存在该老师";
            return $this->return_data;
        }
        $courseware_course = Db::name('courseware_course')->where(['id'=>$id])->find();
        if (!$courseware_course || $courseware_course['level']!=3) {
            $this->return_data['Msg'] = " 主题id有误";
            return $this->return_data;
        }
        $courseware_authorize = Db::name('courseware_authorize')->where(['course_id'=>$courseware_course['id'],'status'=>1,'teacher_id'=>$teacher['id'],'type'=>2])->find();
        if (!$courseware_authorize) {
            $this->return_data['Msg'] = " 很抱歉，该主题未授权！";
            return $this->return_data;
        }
        $coursewares = Db::name('courseware')->where(['course_id'=>$id,'status'=>1])->select();
        if (!$coursewares) {
            $courseware['id'] = 0;
            $courseware['name'] = '';
            $courseware['file'] = [];
            $courseware['has_video'] = 0;
            $courseware['has_pdf'] = 0;
            $courseware['video'] = [];
            $courseware['pdf'] = [];
            $courseware['main_point'] = '';
            $courseware['teaching_aims'] = '';
            $pid3 = $id;
            $courseware_course3 = Db::name('courseware_course')->where(['id'=>$id])->field('pid,name')->find();
            $pid3 = $courseware_course3['pid'];
            $courseware_course_name3 = $courseware_course3['name'];
            $courseware_course2 = Db::name('courseware_course')->where(['id'=>$pid3])->field('pid,name')->find();
            $pid2 = $courseware_course2['pid'];
            $courseware_course_name2 = $courseware_course2['name'];
            $courseware_course1 = Db::name('courseware_course')->where(['id'=>$pid2])->field('pid,name')->find();
            $pid1 = $courseware_course2['pid'];
            $courseware_course_name1 = $courseware_course1['name'];
            $this->return_data["Code"] = 0;
            $this->return_data['Msg'] = "成功";
            $this->return_data['Data'] = ['courseware'=>$courseware,'courseware_course_name3'=>$courseware_course_name3,'courseware_course_name2'=>$courseware_course_name2,'courseware_course_name1'=>$courseware_course_name1];
            return $this->return_data;
        }
        $courseware = $coursewares[0];
        $courseware['has_video'] = 0;
        $courseware['has_pdf'] = 0;
        $courseware['video'] = [];
        $courseware['pdf'] = [];
        $courseware['file'] = [];
        foreach ($coursewares as $k => $v) {
            if (isset($v['file']) && $v['file']) {
                $files = json_decode($v['file'],1);
                $courseware['file'] = array_merge($courseware['file'],$files);
            }
        }
        // if (isset($courseware['file']) && $courseware['file']) {
        //     $courseware['file'] = json_decode($courseware['file'],1);
            if (is_array($courseware['file']) && count($courseware['file'])) {
                foreach ($courseware['file'] as $key => &$value) {
                    $multi_file = [];
                    $ex = explode(',', trim($value[1]));
                    if (count($ex)) {
                        foreach ($ex as $k => &$mf) {
                            // 过滤掉p p t
                            if (explode('.', $mf)[1]=='ppt' || explode('.', $mf)[1]=='pptx') continue;
                            $mf_name = Db::name('file')->where(['path'=>$mf])->value('name');
                            if (!$mf_name) {
                                if ($value[2]=='视频') {
                                    $mf_name = '视频';
                                } else {
                                    $mf_name = '文件';
                                }
                            }
                            if (strpos($mf_name, 'GSK')!==false) {
                                $mf_name = substr($mf_name, 6);
                            } elseif (strpos($mf_name, 'GSP')!==false) {
                                $mf_name = substr($mf_name, 6);
                            } elseif (strpos($mf_name, 'GSPE')!==false) {
                                $mf_name = substr($mf_name, 7);
                            }
                            $mf = config('upload_domain').urlencode($mf);
                            $multi_file[$k] = ['mf_name'=>$mf_name,'mf'=>$mf];
                        }
                    }
                    $value[3] = $multi_file;
                    if ($value[2]=='视频') {
                        $courseware['has_video'] = 1;
                        $courseware['video'] = array_merge($courseware['video'],$multi_file);
                    } else {
                        $courseware['has_pdf'] = 1;
                        $courseware['pdf'] = array_merge($courseware['pdf'],$multi_file);
                    }
                }
            }
        // }
        $courseware_course3 = Db::name('courseware_course')->where(['id'=>$id])->field('pid,name')->find();
        $pid3 = $courseware_course3['pid'];
        $courseware_course_name3 = $courseware_course3['name'];
        $courseware_course2 = Db::name('courseware_course')->where(['id'=>$pid3])->field('pid,name')->find();
        $pid2 = $courseware_course2['pid'];
        $courseware_course_name2 = $courseware_course2['name'];
        $courseware_course1 = Db::name('courseware_course')->where(['id'=>$pid2])->field('pid,name')->find();
        $pid1 = $courseware_course2['pid'];
        $courseware_course_name1 = $courseware_course1['name'];
        $this->return_data["Code"] = 0;
        $this->return_data['Msg'] = "成功";
        $this->return_data['Data'] = ['courseware'=>$courseware,'courseware_course_name3'=>$courseware_course_name3,'courseware_course_name2'=>$courseware_course_name2,'courseware_course_name1'=>$courseware_course_name1];
        return $this->return_data;
    }

}
